<template>
    <div class="container">
        <h3>新增</h3>
        <el-form :model="ruleForm" ref="ruleForm" :rules="rules" :label-position="labelPosition" label-width="120px" class="demo-ruleForm">
			<el-row v-if="!scflag">
				<el-col :span="12">
					<el-form-item label="工艺名称：" prop="name">
						<el-input placeholder="请输入内容" v-model="ruleForm.name" style="width:300px"></el-input>
					</el-form-item>
					<el-form-item label="执行标准：">
                        <el-upload
                            class="upload-poster"
                                action="https://jsonplaceholder.typicode.com/posts/"
                                :show-file-list="false"
                                :on-change="imgPreview"
                                :auto-upload="false">
                                <img v-if="standardsImg" :src="standardsImg" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                        jpg、png、gif格式，60x60像素，不超过2MB
                    </el-form-item>
				</el-col>
				<el-col :span="10">
					<el-form-item label="关联品名：" prop="productName">
						<el-select v-model="ruleForm.productName"  value-key="id" filterable placeholder="请选择" style="width: 300px;">
							<el-option
								v-for="item in basesourcelist"
								:key="item.id"
								:label="item.name"
								:value="item.name"
							>
							{{item.name}}
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>

			</el-row>

            <!--   生产系统新增   -->
            <el-row v-if="scflag">
				<el-col :span="12">
                    <el-form-item label="物料类型：" prop="materialCode">
						<el-select v-model="ruleForm.materialCode" placeholder="请选择" style="width: 300px;" @change="getmaterialname">
                            <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                        </el-select>
					</el-form-item>
					<el-form-item label="工艺名称：" prop="processName">
						<el-input placeholder="请输入内容" v-model="ruleForm.processName" style="width:300px"></el-input>
					</el-form-item>
                    <el-form-item label="执行标准：" prop="standard">
						<el-input placeholder="请输入内容" v-model="ruleForm.standard" style="width:300px"></el-input>
					</el-form-item>

				</el-col>
				<el-col :span="10">
					<el-form-item label="物料名称：" prop="materialName">
						<el-select v-model="ruleForm.materialName"  value-key="id" filterable @change="materialNameChange" placeholder="请选择" style="width: 300px;">
							<el-option
								v-for="item in basesourcelist"
								:key="item.id"
								:label="item.materialName"
								:value="item"
							>
							</el-option>
						</el-select>
					</el-form-item>
                    <el-form-item label="批准文号：" prop="approvalNumber">
						<el-input placeholder="请输入内容" v-model="ruleForm.approvalNumber" style="width:300px"></el-input>
					</el-form-item>
                    <el-form-item label="标准：">
                        <el-upload
                            class="upload-poster"
                                action="https://jsonplaceholder.typicode.com/posts/"
                                :show-file-list="false"
                                :on-change="imgPreview"
                                :auto-upload="false">
                                <img v-if="standardsImg" :src="standardsImg" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                        jpg、png、gif格式，60x60像素，不超过2MB
                    </el-form-item>
				</el-col>

			</el-row>

            <el-row v-if="!scflag">
                <el-table
                    :data="tableData"
                    border
                    style="margin-top:20px;"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                >
					<el-table-column prop="sort" sortable label="排序">
						<template slot-scope="scope">
							<el-input v-model="scope.row.sort" placeholder="请输入内容" style="width:200px;"></el-input>

						</template>
					</el-table-column>
					<el-table-column prop="checkName" sortable label="标准名称">
						<template slot-scope="scope">
							<el-input v-model="scope.row.standards" placeholder="请输入内容" style="width:200px;"></el-input>

						</template>
					</el-table-column>

                    <!-- <el-table-column prop="createTime" sortable label="添加时间"></el-table-column> -->
                    <el-table-column prop="basis" sortable label="检测标准文件">
                        <template slot-scope="scope">
							<el-input v-model="scope.row.specification" placeholder="请输入内容" style="width:400px;"></el-input>

                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="150" align="center">
                        <template slot-scope="scope">
                            <el-button
                                type="text"
                                style="color:red;"

                                @click="handleDelete1(scope.$index, scope.row)"
                            >删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-row>

            <!--   生产系统工序     -->
            <el-row v-if="scflag">
                <el-table
                    :data="tableData1"
                    border
                    style="margin-top:20px;"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                >
					<el-table-column prop="orders" sortable label="工序">
						<template slot-scope="scope">
							<el-input v-model="scope.row.orders" placeholder="请输入内容" style="width:200px;"></el-input>

						</template>
					</el-table-column>
					<el-table-column prop="processName" sortable label="工序名称">
						<template slot-scope="scope">
							<el-input v-model="scope.row.processName" placeholder="请输入内容" style="width:200px;"></el-input>

						</template>
					</el-table-column>

                    <!-- <el-table-column prop="createTime" sortable label="添加时间"></el-table-column> -->
                    <el-table-column prop="processDetails" sortable label="工序规范">
                        <template slot-scope="scope">
							<el-input v-model="scope.row.processDetails" placeholder="请输入内容" style="width:400px;"></el-input>

                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="150" align="center">
                        <template slot-scope="scope">
                            <el-button
                                type="text"
                                style="color:red;"

                                @click="handleDelete2(scope.$index, scope.row)"
                            >删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-row>
			<el-button class='theme-button' style="margin-top:20px;" @click="addlist">添加一条</el-button>
			<el-form-item class="footerFixed" label-width="0px">
				<div class='fixed'>
                    <el-button class='theme-button' @click="submitrule('ruleForm')">提交</el-button>
                    <el-button @click="backPage">返回</el-button>
                </div>
			</el-form-item>

        </el-form>
    </div>
</template>

<script>
	import {technology_save,basesource_findByAll,technology_findById,model_crop_loadbind} from "@/request/api"
	import {scTechnology_save,materialManagement_selectAll,scTechnology_selectId,scTechnology_update} from "@/request/produceApi"
  import {materialManagement_findBylistNoPage} from '../../../../request/produceApi';  //生产工艺工序

    export default {
        data() {
            return {
                basesourcelist:[],
                tableData:[{
					sort:1,
					checkName:'',
					basis:''
                }],
                tableData1:[{   //生产系统工序
					orders:1,
					processName:'',
                  scflag: false,
					processDetails:''
                }],
                city:'',
                area:'',
                isShow:false,
                standardsImg:'',
                // options: regionData,
                selectedOptions: [],
                labelPosition:'right',
                allMessage: '',
                ruleForm: {},
                rules:{},
                scflag: false,
                options: [{
                    value: '成品',
                    label: '成品'
                    }, {
                    value: '半成品',
                    label: '半成品'
                }],
                scvalue: '',
                id: ''
            };
        },
        mounted(){

            this.id = this.$route.query.id
            if(this.id == undefined){
              // this.scflag = true
            }else{
                this.init()
            }
          this.getname()
        },
        methods: {
          getname(){
            let url = localStorage.getItem('lj');
            // console.log(url)
            if(url == "生产") {
              this.scflag = true
            } else {
              this.scflag = false
              console.log(1)
              model_crop_loadbind("").then((res)=>{
                this.basesourcelist = res.data
              })
            }
          },
          getmaterialname(val){
            this.getproductname(val)

          },
          handleDelete2(index,row){
            this.tableData1.splice(index,1)
          },
			handleDelete1(index,row){
				this.tableData.splice(index,1)
            },
            //生产系统物料选择
			materialNameChange(e) {
                this.ruleForm.materialId = e.id
                this.ruleForm.materialName = e.materialName
            },
			addlist(){
				let sort = this.tableData.length + 1
				let sort1 = this.tableData1.length + 1
				this.tableData.push({sort:sort,checkName:'',basis:''})
				this.tableData1.push({orders:sort1,processName:'',processDetails:''})
            },
            //品名数据
            getproductname(val){
                let url = localStorage.getItem('lj');
                if(url == "生产") {
                  this.scflag = true
                  materialManagement_findBylistNoPage({materialType:val}).then((res) =>{
                      this.basesourcelist = res.data
                  })
                } else {

                }
            },
            // 编辑获取数据
            init(){
                let lj = localStorage.getItem('lj')
                if(lj == '生产'){
                    let scId = {
                        id: this.id
                    }
                    scTechnology_selectId(scId).then((res) =>{
                        console.log(res,'1212');
                        this.ruleForm = res.data
                        this.standardsImg = this.$store.state.pathimg + this.ruleForm.standardImg
                        this.tableData1 = res.data.specification
                    })
                } else {
                    technology_findById(this.id).then((res)=>{
                        this.ruleForm = res.data
                        this.standardsImg = this.$store.state.plantImg + this.ruleForm.standardsImg
                        if(this.ruleForm.technologies){
                            this.tableData = this.ruleForm.technologies
                        }
                    })
                }
            },

            // 返回
            backPage () {
                this.$router.go(-1);
            },
            // 新增
            submitrule(formName) {
                let url = localStorage.getItem('lj');
                // let url = '1234';
                if(url == "生产") {
                    let user_id = JSON.parse(localStorage.getItem('userid'));
                    let company_id = localStorage.getItem('companyId');
                    let formdata = {}
                    var obj = {
					Y: new Date().getFullYear(),
					M: new Date().getMonth() + 1,
					D: new Date().getDate(),
					H: new Date().getHours(),
					Mi: new Date().getMinutes(),
					S: new Date().getSeconds()
					}
					if(obj.H < 10) obj.H = '0' + obj.H
					if(obj.Mi < 10) obj.Mi = '0' + obj.Mi
					if(obj.S < 10) obj.S = '0' + obj.S
					var time = ' ' + obj.H + ':' + obj.Mi + ':' + obj.S
                    var times = obj.Y + '-' + obj.M + '-' + obj.D + time;

                    formdata = this.ruleForm
                    if(this.id != undefined){
                        formdata.id = this.ruleForm.id    //id
                        formdata.user_id = this.ruleForm.userId      //用户id
                        formdata.company_id = this.ruleForm.companyId      //公司id
                        formdata.createtime = this.ruleForm.createtime      //时间
                        for(var a=0; a<this.tableData1.length; a++){
                            this.tableData1[a].id = this.tableData1[a].id
                            this.tableData1[a].user_id = this.tableData1[a].userId
                            this.tableData1[a].company_id = this.tableData1[a].companyId
                            this.tableData1[a].createtime = times
                            this.tableData1[a].technologyId = this.tableData1[a].technologyId   //工序id
                        }
                    }else {
                        formdata.id = ""    //id
                        formdata.user_id = user_id      //用户id
                        formdata.company_id = company_id      //公司id
                        formdata.createtime = times      //时间
                        for(var a=0; a<this.tableData1.length; a++){
                            this.tableData1[a].id = ""
                            this.tableData1[a].user_id = user_id
                            this.tableData1[a].company_id = company_id
                            this.tableData1[a].createtime = times
                            this.tableData1[a].technologyId = ""   //工序id
                        }
                    }

                    formdata.file = this.ruleForm.files
                    let formdatas = new FormData()
                    formdata.specification = this.tableData1
                    for(var a in formdata){
                        if(formdata[a] == null || formdata[a] == "null"){
                            formdata[a] = ""
                            formdatas.append(a,'')
				        }else{
                            formdatas.append(a,formdata[a])
				        }
                    }
                    for(var i=0;i<formdata.specification.length;i++){
                        // if(formdata.specification[i].files != "" && formdata.specification[i].files != null){
                        //     formdata.append("files",this.cropList[i].files)
                        // }
                        var s = "specification[" + i + "].id"
                        formdatas.set(s,formdata.specification[i].id)
                        var d = "specification[" + i + "].user_id"
                        formdatas.set(d,formdata.specification[i].user_id)
                        var f = "specification[" + i + "].company_id"
                        formdatas.set(f,formdata.specification[i].company_id)
                        var g = "specification[" + i + "].createtime"
                        formdatas.set(g,formdata.specification[i].createtime)
                        var h = "specification[" + i + "].technologyId"
                        formdatas.set(h,formdata.specification[i].technologyId)
                        var j = "specification[" + i + "].orders"
                        formdatas.set(j,formdata.specification[i].orders)
                        var k = "specification[" + i + "].processName"
                        formdatas.set(k,formdata.specification[i].processName)
                        var l = "specification[" + i + "].processDetails"
                        formdatas.set(l,formdata.specification[i].processDetails)
                    }
                    // for (var value of formdatas.values()) {
                    //     console.log(value,'2424');
                    // }
                    if(this.id !=undefined){
                        scTechnology_update(formdatas).then((res) =>{
                            this.$notify({
                                title: '提示',
                                message: '修改成功',
                                type: 'success',
                                duration:1000
                            });
                            this.$router.go(-1)
                        })
                    } else {
                        scTechnology_save(formdatas).then((res) =>{
                            this.$notify({
                                title: '提示',
                                message: '保存成功',
                                type: 'success',
                                duration:1000
                            });
                            this.$router.go(-1)
                        })
                    }
                } else {
                    let formdata = new FormData()
                    this.ruleForm.technologiesList = JSON.stringify(this.tableData)
                    // console.log(this.ruleForm,'141414');
				    for(var a in this.ruleForm){
                        if(this.ruleForm[a] == null || this.ruleForm[a] == "null"){
                            this.ruleForm[a] = ""
				            formdata.append(a,'')
				        }else{
                            formdata.append(a,this.ruleForm[a])
				        }
                    }
                    // console.log(formdata,'121212');
                    // console.log(formdatas,'121212');
                     for (var value of formdata.values()) {
                        // console.log(value,'2424');
                    }
                    technology_save(formdata).then((res)=>{
                        this.$notify({
                            title: '提示',
				            message: '保存成功',
				            type: 'success',
				            duration:1000
				        });
				        this.$router.go(-1)
			        })
                }
            },

            imgPreview(file,fileList) {
                this.standardsImg =  URL.createObjectURL(file.raw);
                let fileName = file.name;
                let regex = /(.jpg|.gif|.png|.jpeg)$/;
                if (regex.test(fileName.toLowerCase())) {
                    this.ruleForm.files = file.raw
                    this.ruleForm.standardsImg = file.name
                } else {
                    this.$message.error('请选择图片文件');
                }
            },


        }
    }
</script>

<style scoped lang="less">
.demo-ruleForm{
    margin-top: 10px;
}
.demo-ruleForm .el-radio--small.is-bordered{
    width: 120px !important;
    margin-right: 10px !important;
}
.box{
    width: 85%;
    margin-bottom: 15px;
    dl{
        margin-bottom: 20px;
        overflow: hidden;
        dt{ margin-bottom: 5px; font-size: 14px;}
        dd{ font-weight: 500; font-size: 12px; float: left; width: 50%; line-height: 24px;}
    }
    dl:last-child{
        margin-bottom: 0;
    }
    .el-col-11{
        height: 200px;
        overflow-y: auto;
        margin-left: 10px;
        border-left: 1px solid #EBEEF5;
        padding-left: 10px;
        p{ color: #303133;}
        .record-tip-con{
            padding-top: 10px;
        }
    }
}

 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    width:180px;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .el-upload--text{
      width:180px;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
